import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useMutation } from '@tanstack/react-query';
import { Button, Form, Input, message, Space } from 'antd';
import { useNavigate } from 'react-router-dom';

import api from '@/apis/api';
import { Messages } from '@/components/Messages/Messages';
import { Logger } from '@/components/useLogger';
import { systemType } from '@/constant/systemType';
import localINFO from '@/utils/localInfo';
import { UsbLoginUser } from '@/utils/usbKey/login';

import login from '../../img/background1.svg';
import logo1 from '../../img/logo1.png';
import logo2 from '../../img/logo2.png';
import styles from './style.module.less';

const Login = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 获取后端登录需要的随机数
  const GetRandom = useMutation({
    mutationFn: (params: any) => api.GenRandom(params),
    onSuccess: (data: any) => {
      if (!data?.success) {
        message.open({
          type: 'error',
          key: 'login',
          content: `获取随机数失败, ${data?.message}`,
        });
      }
    },
    onError: () => {
      message.open({
        type: 'error',
        key: 'login',
        content: '获取随机数失败',
      });
    },
  });

  // 登录
  const Login = useMutation({
    mutationFn: (params: any) => api.Login(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        const token = res?.data?.token?.access_token;
        const roleId = res?.data?.grant === 0 ? 1 : 2; // 0-管理员 1-操作员
        // 如果登录成功清除之前所有的存储内容
        localINFO.clear();
        // 保存token
        localINFO.setRoleId(roleId);
        localINFO.setToken(token);

        navigate('/system');
        message.open({
          key: 'login',
          type: 'success',
          content: '登录成功',
        });
      } else {
        message.open({
          type: 'error',
          key: 'login',
          content: `登录失败，${res?.message}`,
        });
      }
    },
    onError: () => {
      message.open({
        type: 'error',
        key: 'login',
        content: '登录失败',
      });
    },
  });

  const handleClickFinish = async (values: any) => {
    if (values.name && values.password) {
      try {
        message.open({
          type: 'info',
          key: 'login',
          content: '登录中...请稍侯',
        });

        const res = await GetRandom.mutateAsync({
          name: values.name,
        });
        const random = res?.data?.random_number;
        if (random) {
          const usbLoginRes: {
            digest: string;
            signature: string;
            originData: string;
          } = await UsbLoginUser(random);

          Login.mutate({
            grant_type: undefined,
            username: values.name,
            password: values.password,
            scope: undefined,
            client_id: usbLoginRes?.originData,
            client_secret: usbLoginRes?.signature,
          });
        }
      } catch (error: any) {
        Logger(error.message);
        Messages.error(
          'USBkey登录角色失败，请确认已注册USBkey角色并检查USBkey是否插入！',
        );
      }
    }
  };

  return (
    <>
      <div className={styles.LoginPage}>
        {/* 左边背景 */}
        <div className={styles.Leftdiv}>
          <img
            src={login}
            alt="Login"
            style={{
              width: '50vw',
              height: '100vh',
              objectFit: 'cover',
            }}
          />
        </div>
        {/* 登录盒子 */}
        <div className={styles.LoginBox}>
          <div className={styles.Title}>
            <img
              src={systemType === 'school' ? logo1 : logo2}
              alt="Logo"
              className={styles.Logo}
            />
            {systemType === 'school' ? (
              <h1>哈尔滨理工大学 国密服务器密码机</h1>
            ) : (
              <h1>中数国密商用服务器密码机</h1>
            )}
          </div>

          {/* 表单部分 */}
          <div className="form">
            <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
              <Form style={{ width: '100%' }} form={form} onFinish={handleClickFinish}>
                <div>
                  <Form.Item
                    name={'name'}
                    rules={[{ required: true, message: '请输入账号!' }]}
                  >
                    <Input
                      prefix={<UserOutlined />}
                      placeholder="请输入账号"
                      maxLength={30}
                    />
                  </Form.Item>

                  <Form.Item
                    name={'password'}
                    rules={[{ required: true, message: '请输入密码!' }]}
                  >
                    <Input.Password
                      prefix={<LockOutlined />}
                      type="password"
                      placeholder="请输入密码"
                      minLength={4}
                    />
                  </Form.Item>

                  {/* <div style={{ textAlign: 'right' }}>
                    没有账号?{' '}
                    <a
                      onClick={() => {
                        navigate('/init');
                      }}
                    >
                      点此注册
                    </a>
                  </div> */}

                  <Form.Item>
                    <Button
                      type="primary"
                      htmlType="submit"
                      style={{ width: '450px', marginTop: '24px' }}
                    >
                      登录
                    </Button>
                  </Form.Item>
                </div>
              </Form>
            </Space>
          </div>
        </div>
      </div>
    </>
  );
};

export default Login;
